﻿using System.Xml.Linq;
using IDeal.Extensions;
using IDeal.Models;
using IDeal.Services;

namespace IDeal.Serialization
{
    internal class TransactionRequestXmlWriter : XmlMessageWriter<TransactionRequest>
    {
        public TransactionRequestXmlWriter(IIDealServices iDealServices) : base(iDealServices)
        {
        }

        protected override string RootElementName
        {
            get { return "AcquirerTrxReq"; }
        }

        protected override string GetHashSource(TransactionRequest instance)
        {
            return 
                instance.CreatedDateTimeStamp.ToIDealFormat() +
                instance.IssuerId +
                instance.MerchantId +
                instance.SubId +
                instance.MerchantReturnUrl +
                instance.PurchaseId +
                instance.Amount +
                instance.Currency +
                instance.Language +
                instance.Description +
                instance.EntranceCode;
        }

        protected override void SetupRootElement(TransactionRequest instance, XElement rootElement)
        {
            var signature = CreateSignature(instance);

            rootElement.Add(new XElement
            (
                Ns + "Issuer",
                new XElement(Ns + "issuerID", instance.IssuerId)
            ));

            rootElement.Add(new XElement
            (
                Ns + "Merchant",
                new XElement(Ns + "merchantID", instance.MerchantId),
                new XElement(Ns + "subID", instance.SubId),
                new XElement(Ns + "authentication", "SHA1_RSA"),
                new XElement(Ns + "token", signature.Fingerprint),
                new XElement(Ns + "tokenCode", signature.Token),
                new XElement(Ns + "merchantReturnURL", instance.MerchantReturnUrl)
            ));

            rootElement.Add(new XElement
            (
                Ns + "Transaction",
                new XElement(Ns + "purchaseID", instance.PurchaseId),
                new XElement(Ns + "amount", instance.Amount),
                new XElement(Ns + "currency", instance.Currency),
                new XElement(Ns + "expirationPeriod", "PT3M30S"),
                new XElement(Ns + "language", instance.Language),
                new XElement(Ns + "description", instance.Description),
                new XElement(Ns + "entranceCode", instance.EntranceCode)
            ));
        }
    }
}
